// This file is part of Mongoose project, http://code.google.com/p/mongoose

var blockUntilDone = null;
var enableRefresh = true;
var timeoutId = 0;

// the message types e.g show, alert, warn, setValue ... 
var messageTypes = new Array();

var types = new Array();

var message = {
	status: '',
	message: '',
	data: '',
	lastMessageId: 0,
	maxVisibleMessages: 50,
	getMessagesIntervalMs: 1000
};

var addMessage = function(data){
    var row = $('<div>').addClass('message-row').appendTo('#msgHistory');
    var timestamp = (new Date(data.timestamp * 1000)).toLocaleTimeString();
    $('<span>')
      .addClass('message-timestamp')
      .html('[' + timestamp + ']')
      .prependTo(row);
    $('<span>')
      .addClass('message-user')
      .html(data.message)
      .appendTo(row);
    message.lastMessageId = Math.max(message.lastMessageId, data.id) + 1;
};


/////////////////////////////// TYPES ///////////////////////////////

var refreshAvailableTypesHandler = function(data){
	types = new Array();

	  $.each(data, function(index, entry) {
		  types.push(entry);
	  });
};

var refreshAvailableTypes = function(){
	  $.ajax({
	    dataType: 'json',
	    url: '/ajax/getAvailableTypes',
	    success: refreshAvailableTypesHandler,
	    error: function(ev) {
	    }
	  });
};
/////////////////////////////// TYPES END ///////////////////////////////

/////////////////////////////// FILEUPLOAD ///////////////////////////////

var refreshUploadedFilesHandler = function(data){
	while ($('#AvailableUploadedFiles tbody').children().length > 1) {
		$('#AvailableUploadedFiles tr:nth-child(2)').remove();
	}

	$.each(data, function(index, entry) {
		var background = '';
		if(index % 2 == 0){
			background = " style='background-color: #ececec;'";
		}
		var row = $('<tr' + background + '>').appendTo('#AvailableUploadedFiles');
		$('<td>')
			.html(entry.filename)
			.prependTo(row);
		$('<td>')
			.html(entry.date)
			.appendTo(row);
		$('<td>')
			.addClass('action')
			.addClass('rowAction')
			.html('import')
			.click(function() {
				importUploadedFile(entry.filename);
			})
			.appendTo(row);
		$('<td>')
			.addClass('action')
			.addClass('rowAction')
			.html('delete')
			.click(function() {
				deleteUploadedFile(entry.filename);
			})
			.appendTo(row);
	});
	enableRefresh = true;
};

var refreshUploadedFiles = function(){
	$.ajax({
		dataType: 'json',
		url: '/ajax/getUploadedFiles',
		beforeSubmit: function() {
			enableRefresh = false;
		},
		success: refreshUploadedFilesHandler,
		error: function(ev) {
	}
	});
};

var deleteUploadedFileHandler = function(data){
  refreshUploadedFiles();
};

var deleteUploadedFile = function(_fileName){
  $.ajax({
    dataType: 'json',
    url: '/ajax/deleteUploadedFile',
    data: {fileName: _fileName},
    success: deleteUploadedFileHandler,
    error: function(ev) {
    }
  });
};

var importUploadedFileHandler = function(data){
  // disable everything
  // wait until we get an 'import finished message'
  // see some lines below
  
  // here we just can get an 
  //   Task xxxxxxxxx failed.
  //   Task xxxxxxxxx started.

  result = data.message.match(/Task\s(\d.+)\s(.+)/);
  if (result && result.length >= 2){
	//result[1] == number
	//result[2] == status
	if(result[2] == 'started'){
		blockUntilDone = result[1];
		$('#svgFileUploadFileChooser').attr("disabled", true);
		$('#svgFileUploadSubmitter').attr("disabled", true);
		$('.rowAction').removeClass('action');
	  
		var $out = $('#importSvgFileResult');
		$out.removeClass('errorMsg');
		$out.removeClass('warnMsg');
		$out.addClass('warnMsg');
		$out.html('Please wait until the import is finished.');
	} else {
		var $out = $('#importSvgFileResult');
		$out.removeClass('errorMsg');
		$out.removeClass('warnMsg');
		$out.addClass('errorMsg');
		$out.html("Can't import file. Details can be found in the Message box  ...");
	}
	
  }
};

var importUploadedFile = function(_fileName){
  $.ajax({
    dataType: 'json',
    url: '/ajax/importUploadedFile',
    data: {fileName: _fileName},
    success: importUploadedFileHandler,
    error: function(ev) {
    }
  });
};

/////////////////////////////// FILEUPLOAD END ///////////////////////////////

var refreshMessageView = function(data){
  $.each(data, function(index, entry) {
    addMessage(entry);
    
    // wait until we get an 'import finished message'
	// see some lines above
    if(blockUntilDone != null){
	  result = entry.message.match(/Task\s(\d.+)\s(.+)/);
	  if (result && result.length >= 2 && result[1] == blockUntilDone && (result[2] == 'done' || result[2] == 'failed')){
		$('#svgFileUploadFileChooser').attr("disabled", false);
		$('#svgFileUploadSubmitter').attr("disabled", false);
		$('.rowAction').addClass('action');
		blockUntilDone = null;
	  }
    }
  });
  while ($('#msgHistory').children().length > message.maxVisibleMessages) {
    $('#msgHistory div:first-child').remove();
  }
};

getServerMessages = function() {

  if(enableRefresh){
    $.ajax({
      dataType: 'json',
      url: '/ajax/get_messages',
      data: {last_id: message.lastMessageId},
      success: refreshMessageView
    });
  }
  timeoutId = window.setTimeout(getServerMessages, message.getMessagesIntervalMs);
};

var handleMenuItemClick = function(ev) {
  $('.menu-item').removeClass('menu-item-selected');  	// Deselect menu buttons
  $(this).addClass('menu-item-selected');  				// Select clicked button
  $('.main').addClass('hidden');  						// Hide all main windows
  $('#' + $(this).attr('name')).removeClass('hidden');  // Show main window
  if($(this).attr('name') == 'import'){
    refreshUploadedFiles();
  } else if ($(this).attr('name') == 'properties'){
	  refreshAvailableProperties();
  } else {
	    refreshAvailableAALItems();
	    refreshAvailableTypes();
	    refreshAvailableTemplates();
  }
};

var saveMessageTypes = function(data){
  $.each(data, function(index, entry) {
    messageTypes.push(entry);
  });
};

getMessageTypes = function() {
  if(enableRefresh){
    $.ajax({
      dataType: 'json',
      url: '/ajax/getMessageTypes',
      success: saveMessageTypes
    });
  }
};

$(document).ready(function() {
	$('.menu-item').click(handleMenuItemClick);
	getMessageTypes();
	refreshAvailableAALItems();
	refreshAvailableTypes();
	refreshAvailableTemplates();
	// refreshAvailableTemplateImages();
	getServerMessages();
	$('#svgFileUpload').ajaxForm({
		dataType: 'json',
		beforeSubmit: function() {
			enableRefresh = false;
			var $out = $('#svgFileUploadResult');
			$out.html('Uploading file....');
		},
		success: function(data){
			var $out = $('#svgFileUploadResult');

			$out.removeClass('errorMsg');
			$out.removeClass('warnMsg');
			if(data.status = 'WARN'){
				$out.addClass('warnMsg');
			} else if(data.status = 'ERROR'){
				$out.addClass('errorMsg');
			}
			$out.append(data.message);
			refreshUploadedFiles();
		}
	});
});